'''
Created on Sep 4, 2011

@author: david
'''
from app.G6.model import Account
import logging

class AccountException(Exception):
    """
    Cannot have two accts w/ same email
    addr.
    """ 
    def __init__(self,str):
        Exception.__init__(self,str)
        
class AccountAgent(object):
    """
    Manage all of the business
    of user accounts. 
    """
    
    def __init__(self):
        pass
    
    def create(self,args):
        """
        Create a new G6 account
        """
        acct = None
        
        # check for existing acct
        tst = Account.gql("WHERE uid = :1", args['uid'])
        if tst.count(1) > 0:
            # got one, check the password
            acct = tst.get()
            if acct.pwd == args['pwd']:
                # already good, just use it
                acct.dt_last = None
                acct.put()
                logging.debug("~~ Using existing account")
            else:
                # unauthorized duplication    
                raise AccountException("Account %s already exsists." % args['uid'])
            
        else:
            # create the account and move on
            acct = Account(uid=args['uid'],pwd=args['pwd'])
            acct.name = "%s::%s" % (args['fname'],args['lname'])
            acct.aid = "AC%s" % Account.all().count()
            acct.status = 1
            acct.put()
            
            logging.info("++ Created new user account %s" % args['uid'])
            
        return acct
    
    def update(self,acct,args):
        """
        update account attributes
        """
        acct.pwd = args['pwd']
        acct.name = "%s::%s" % (args['fname'],args['lname'])
        acct.status = int(args['status'])
        acct.dt_last = None
        acct.put()
    
        return acct
    
    def fetch(self,uid,pwd,createEmpty=False):
        """
        Get user account
        """
        acct = None
        
        # new account please
        if not uid and createEmpty:
            acct = Account()
        else:
            # fetch existing accout
            qry = Account.gql('WHERE uid = :1 and pwd = :2',uid,pwd)
            if qry.count(1):
                # got it
                acct = qry.get()     
            else:
                # don't got it
                raise AccountException("Account %s not found or not authorized." % uid)
        
        # return results
        return acct
    